#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

static WiFiUDP* UdpServer = new WiFiUDP();
const unsigned short udpPort = 11111;

// 获取 MAC 字符串
String macToString()
{
  uint8_t mac[6];
  WiFi.macAddress(mac);
  char buf[18];
  sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
          mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
  return String(buf);
}

// 创建 UDP 对象
void initUDP()
{
  if (UdpServer->begin(udpPort)) {
    Serial.printf("✅ Listening for broadcast on port %d\n", udpPort);
  } else {
    Serial.println("❌ UDP begin failed!");
  }
  Serial.printf("Local IP: %s\n", WiFi.localIP().toString().c_str());
}

// 处理 UDP 数据
void handleUDPPacket()
{
  int len = UdpServer->parsePacket();
  if (len > 0) {
    String msg;
    msg.reserve(len);
    while (UdpServer->available()) {
      msg += char(UdpServer->read());
    }

    IPAddress remoteIP = UdpServer->remoteIP();
    int remotePort = UdpServer->remotePort();

    Serial.printf("📩 Recv '%s' from %s:%d\n", msg.c_str(), remoteIP.toString().c_str(), remotePort);

    if (msg == "DISCOVER") {
      String resp = "{\"ip\":\"" + WiFi.localIP().toString() + "\",\"mac\":\"" + macToString() + "\"}";
      UdpServer->beginPacket(remoteIP, remotePort);
      UdpServer->print(resp);
      UdpServer->endPacket();
      Serial.println("📤 Responded with device info");
    }
  }
}
